package org.september.pisces.user.permission.controller;


import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.september.core.constant.enums.DeleteFlag;
import org.september.core.exception.BusinessException;
import org.september.pisces.user.permission.entity.SystemRole;
import org.september.pisces.user.permission.service.OperationLogService;
import org.september.pisces.user.permission.service.PiscesPermissionService;
import org.september.pisces.user.permission.service.SystemRoleService;
import org.september.pisces.user.permission.vo.PermissionTreeNode;
import org.september.pisces.user.permission.vo.TreeItem;
import org.september.simpleweb.controller.BaseController;
import org.september.simpleweb.model.ResponseVo;
import org.september.smartdao.CommonDao;
import org.september.smartdao.CommonValidator;
import org.september.smartdao.model.Page;
import org.september.smartdao.model.ParamMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import jakarta.validation.Valid;

@Controller
public class PiscesSystemRoleController extends BaseController {

	private static final String Mapping_Prefix = "/userPermission/systemRole";
	public static final String List_Page = Mapping_Prefix+"/systemRoleList";
	public static final String List_Data = Mapping_Prefix+"/listSystemRoleData";
	
	public static final String Add_Page = Mapping_Prefix+"/addSystemRole";
	public static final String Add_Action = Mapping_Prefix+"/doAddSystemRole";
	
	public static final String Edit_Page = Mapping_Prefix+"/editSystemRole";
	public static final String Edit_Action = Mapping_Prefix+"/doUpdateSystemRole";
	public static final String Delete_Action = Mapping_Prefix+"/delete";
	
	public static final String Grant_Permission_Page = Mapping_Prefix+"/grantPermission";
	public static final String Grant_Permission_Action = Mapping_Prefix+"/doGrantPermission";
	public static final String Clone_Action = Mapping_Prefix+"/doClone";
	
	@Autowired
	private CommonDao commonDao;

	@Autowired
	private CommonValidator commonValidator;
	
	@Autowired
	private PiscesPermissionService permissionService;
	
	@Autowired
	private OperationLogService operationLogService;
	
	@Autowired
	private SystemRoleService systemRoleService;
	
	@RequestMapping(value = List_Page)
	public ModelAndView systemRoleList() throws Exception {
		ModelAndView mv = new ModelAndView();
		return mv;
	}

	@ResponseBody
	@RequestMapping(value = List_Data)
	public ResponseVo<Page<SystemRole>> listSystemRoleData(Page<SystemRole> page, String name) throws Exception {
		ParamMap pm = new ParamMap();
		pm.put("name", name);
		page = commonDao.findPageByParams(SystemRole.class, page, "PiscesSystemRole.listSystemRole", pm);
		return ResponseVo.<Page<SystemRole>>BUILDER().setData(page).setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
	}

	@RequestMapping(value = Add_Page)
	public ModelAndView addSystemRole() throws Exception {
		ModelAndView mv = new ModelAndView();
		return mv;
	}

	@ResponseBody
	@RequestMapping(value = Add_Action)
	public ResponseVo<String> doAddSystemRole(@Valid SystemRole systemRole) throws Exception {
		boolean exist = commonValidator.exsits(SystemRole.class, new String[]{"name","deleteFlag"}, new Object[]{systemRole.getName(),DeleteFlag.NotDelete.ordinal()});
		if (exist) {
			throw new BusinessException("角色名称重复，请检查!");
		}
		commonDao.save(systemRole);
		operationLogService.addLog("添加了角色【"+systemRole.getName()+"】");
		return ResponseVo.<String>BUILDER().setData("").setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
	}

	@RequestMapping(value = Edit_Page)
	public ModelAndView editSystemRole(Long id) throws Exception {
		ModelAndView mv = new ModelAndView();
		SystemRole po = commonDao.get(SystemRole.class, id);
		mv.addObject("systemRole", po);
		return mv;
	}

	@ResponseBody
	@RequestMapping(value = Edit_Action)
	public ResponseVo<String> doUpdateSystemRole(@Valid SystemRole systemRole) throws Exception {
		boolean exist = commonValidator.exsitsNotMe(SystemRole.class, new String[]{"name","deleteFlag"}, new Object[]{systemRole.getName(),DeleteFlag.NotDelete.ordinal()}, systemRole.getId());
		if (exist) {
			throw new BusinessException("角色名称重复，请检查!");
		}
		commonDao.update(systemRole);
		operationLogService.addLog("修改角色【"+systemRole.getName()+"】信息");
		return ResponseVo.<String>BUILDER().setData("").setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
	}

	@ResponseBody
	@RequestMapping(value = Delete_Action)
	public ResponseVo<String> delete(Long id) throws Exception {
		SystemRole po = commonDao.get(SystemRole.class, id);
		if (po == null) {
			throw new RuntimeException("数据不存在或已删除");
		}
		po.setDeleteFlag(1);
		commonDao.update(po);
		operationLogService.addLog("删除了角色【"+po.getName()+"】");
		return ResponseVo.<String>BUILDER().setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
	}
	
	@ResponseBody
	@RequestMapping(value = Clone_Action)
	public ResponseVo<String> clone(Long id) throws Exception {
		SystemRole po = commonDao.get(SystemRole.class, id);
		if (po == null) {
			throw new RuntimeException("数据不存在或已删除");
		}
		systemRoleService.cloneRole(po);
		return ResponseVo.<String>BUILDER().setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
	}

    @RequestMapping(value = Grant_Permission_Page)
    public ModelAndView grantPermission(Long roleId , Boolean readonly) throws Exception {
        ModelAndView mv = new ModelAndView();
        Collection<PermissionTreeNode> pdList = permissionService.getAllPermissions();
        List<TreeItem> tiList = new ArrayList<>();
        for(PermissionTreeNode pd: pdList) {
        	for(TreeItem ti : permissionService.toTreeItem(pd)) {
        		if(ti.getParentId()==null) {
        			ti.setParentId("-1");
        		}
        		if(!tiList.contains(ti)) {
        			tiList.add(ti);
        		}
        	}
        }
        permissionService.selectTreeItem(tiList, roleId);
        mv.addObject("itemList", tiList);
        mv.addObject("roleId", roleId);
        mv.addObject("viewonly", readonly==null?false:readonly);
        return mv;
    }

    @ResponseBody
    @RequestMapping(value = Grant_Permission_Action)
    public ResponseVo<String> doGrantPermission(Long roleId, String resources, String remark) throws Exception {
    	SystemRole po = commonDao.get(SystemRole.class, roleId);
    	permissionService.doGrantPermission(roleId, resources);
		operationLogService.addLog("修改了角色【"+po.getName()+"】的权限");
        return ResponseVo.<String>BUILDER().setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
    }
}
